<?php

class ImgMark{
    private static $getInstance;
    private $ori_suffix;            //原图后缀
    private $wa_suffix;             //水印图后缀
    private $ori_img;               //原图路径
    private $water_img;             //水印图片路径
    private $dir;                   //存放路径
    private $name;                  //图片名字


    private function __construct($conf){
        $this->init($conf);
        $this->getImgInfo();
    }

    private function __clone(){

    }

    static function getInstance($conf){
        if(!self::$getInstance instanceof self){
            return self::$getInstance = new self($conf);
        }

        return self::$getInstance;
    }

    private function init($conf){
        $this->name = empty($conf['name']) ? '' : $conf['name'];
        $this->dir = empty($conf['dir']) ? 'imgmark/' : $conf['dir'];
        $this->ori_img = empty($conf['ori_img']) ? '' : $conf['ori_img'];
        $this->water_img = empty($conf['water_img']) ? '' : $conf['water_img'];
    }

    private function getImgInfo(){
        list($ori_w, $ori_h, $ori_type) = getimagesize($this->ori_img);
        list($wa_w, $wa_h, $wa_type) = getimagesize($this->water_img);

        $types = [1 => 'gif', 2 => 'jpeg', 3 => 'png'];

        $this->ori_suffix = $types[$ori_type];
        $this->wa_suffix = $types[$wa_type];
    }

    function make(){
        $preimagecreate = 'imagecreatefrom' . $this->ori_suffix; //原图
        $waterimagecreate = 'imagecreatefrom' . $this->wa_suffix; //新图

        $pre_img = $preimagecreate($this->ori_img);
        $img_desc = $waterimagecreate($this->water_img);

        //水印图片的位置
        $x = 100;
        $y = 100;

        imagecopy($pre_img, $img_desc, 0, 0, $x, $y, 150, 102);

        // header("Content-Type:image/{$types[$ori_type]}");

        $water_img_dir = $this->dir . '/imgmark/';
        if (!is_dir($water_img_dir)) {
            mkdir($water_img_dir, 0777, TRUE);
        }

        $save = 'image' . $this->ori_suffix;
        $save($pre_img, $water_img_dir . 'imgmark' . $this->name);

        imagedestroy($pre_img);
        imagedestroy($img_desc);

        return $water_img_dir . 'imgmark' . $this->name;
    }
}